package com.david.videoapp.exoplayer

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.view.WindowManager
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.ui.PlayerView
import com.david.videoapp.R

class ExoPlayerActivity: Activity() {
    private lateinit var localPlayerView: PlayerView
    private var exoPlayer: ExoPlayer? = null

    @SuppressLint("UnsafeOptInUsageError")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.exoplayer_two)
        localPlayerView = findViewById(R.id.local_player_view)
        localPlayerView.requestFocus()


//        trackSelector = new DefaultTrackSelector(this);
        exoPlayer = ExoPlayer.Builder(
            this,
            DefaultRenderersFactory(this).setMediaCodecSelector(BlackListMediaCodecSelector()),
            DefaultMediaSourceFactory(this)
        ).build()
        localPlayerView.player = exoPlayer


        // Media queue management.
//        exoPlayer.setMediaItem(new MediaItem.Builder().setUri("rtmp://58.200.131.2:1935/livetv/cctv1").build());
//        exoPlayer!!.setMediaItem(MediaItem.Builder().setUri("http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8").build())
        exoPlayer!!.setMediaItem(MediaItem.Builder().setUri("https://v5.1080pzy.co/20220623/6j34CAKX/index.m3u8").build())
//        exoPlayer!!.setMediaItem(MediaItem.Builder().setUri("rtmp://58.200.131.2:1935/livetv/cctv10").build());
        exoPlayer!!.playWhenReady = true
        exoPlayer!!.prepare()

        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }


    override fun onResume() {
        super.onResume()
        if (exoPlayer != null && exoPlayer!!.currentPosition > 0) {
            exoPlayer!!.playWhenReady = true
            //            exoPlayer.seekTo(resumePosition);
        }
    }

    override fun onPause() {
        super.onPause()
        if (exoPlayer != null && exoPlayer!!.playWhenReady) {
//            resumeWindow = exoPlayer.getCurrentWindowIndex();
//            resumePosition = Math.max(0, exoPlayer.getContentPosition());
            exoPlayer!!.playWhenReady = false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //释放播放器
        if (exoPlayer != null) {
            exoPlayer!!.stop()
            exoPlayer!!.release()
            exoPlayer = null
        }
    }
}